package com.frame.jfinal.config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/*******************************************
 * 作用描述：model对象配置xml文件解析
 *******************************************
 * @author LRC
 * @createDate 2015-9-11
 * @version v1.0 
 * @updateRecord 格式：时间，作者，修改说明
 *******************************************
 * 
 */
public class ModelCfgXML {
	
	/**
	 * model配置文件名
	 */
	private String fileName = "ModelMapping.cfg.xml";
	/**
	 * 单例对象
	 */
	private static ModelCfgXML config = new ModelCfgXML();
	
	public static ModelCfgXML getInstance(){
		return config;
	}
	/**
	 * vo值类映射
	 */
	private Map<String,Map<String,Object[]>> voMapping;

	public ModelCfgXML(){
		try{
			voMapping = new HashMap<String, Map<String,Object[]>>();
			InputStream xml = ModelCfgXML.class.getClassLoader().getResourceAsStream(fileName);
			parse(xml);
		}catch(Exception e){
			throw new RuntimeException("加载Model配置文件错误",e);
		}
		
	}

	/*******************************************
	 * 功能描述：解析配置文件
	 *******************************************
	 * @createDate 2015-9-11 by LRC
	 * @param xml
	 * @throws Exception 
	 * @updateRecord 格式：时间，作者，修改说明
	 *******************************************
	 * 
	 */
	public void parse(InputStream xml) throws Exception{
		voMapping.clear();
		//读取xml文件到document对象
		SAXReader reader = new SAXReader();
		Document doc = reader.read(xml);
		//查找vo-mapping
		List<Element> mappings = doc.selectNodes("/models/model-mapping");
		for(Element mapping : mappings){
			Attribute vName = mapping.attribute("datasouce");
			if(vName!=null){
				String _vName = vName.getValue();
				List<Element> classes = mapping.selectNodes("//model-mapping[@datasouce='"+_vName+"']/class");
				if(classes.size()==0)continue;
				Map<String,Object[]> classMapping = new HashMap<String, Object[]>();
				for(Element _class : classes){
					//获取类名
					Attribute cName = _class.attribute("name");
					if(cName==null)continue;
					Attribute bName = _class.attribute("bean");
					if(bName==null)continue;
					Attribute kName = _class.attribute("key");
					Object[] os = new Object[]{kName.getValue(),Class.forName(bName.getValue())};
					classMapping.put(cName.getValue(),os);
				}
				voMapping.put(_vName, classMapping);
			}
		}
	}

	/**
	 * 给定数据源名称和类名称获取对应类的类型
	 * @param dataSource
	 * @param className
	 * @return
	 */
	public Class getClass(String dataSource,String className){
		Map<String,Object[]> mapping = this.voMapping.get(dataSource);
		if(mapping!=null){
			Object[] os = mapping.get(className);
			return (Class) os[1];
		}
		return null;
	}
	
	public Map<String, Map<String, Object[]>> getModelMapping() {
		return voMapping;
	}
	
}
